package com.swind.fast.modules.app.railway.project.service.impl;

import com.swind.fast.common.system.base.service.impl.SwindServiceImpl;
import com.swind.fast.modules.app.railway.task.constant.TaskPointStatusEnum;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectTaskPoint;
import com.swind.fast.modules.app.railway.project.mapper.RailwayProjectTaskPointMapper;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectTaskPointService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.swind.fast.common.util.DateUtils;
import com.swind.fast.common.util.oConvertUtils;

import com.swind.fast.modules.app.railway.task.entity.RailwayTaskPointFile;
import com.swind.fast.modules.app.railway.task.service.IRailwayTaskPointFileService;
import com.swind.fast.modules.app.railway.project.vo.RailwayDataManagementStatisticVo;
import com.swind.fast.modules.app.railway.task.vo.RailwayTaskStatusVo;
import com.swind.fast.modules.app.railway.task.vo.RailwayTestPointStatusVo;
import com.swind.fast.modules.app.railway.task.event.ProjectTaskStatusEvent;
import com.swind.fast.modules.app.railway.task.event.ProjectTaskPointStatusEvent;
import com.swind.fast.modules.app.railway.task.entity.RailwayTaskPointOperationLog;

import org.springframework.context.ApplicationContext;
import com.swind.fast.modules.system.entity.SysUser;
import com.swind.fast.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Optional;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 项目
 */
@Slf4j
@Service
public class RailwayProjectTaskPointServiceImpl extends SwindServiceImpl<RailwayProjectTaskPointMapper, RailwayProjectTaskPoint> implements IRailwayProjectTaskPointService {

    @Autowired
    private IRailwayTaskPointFileService railwayTaskPointFileService;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public IPage<RailwayProjectTaskPoint> pageMain(Page<RailwayProjectTaskPoint> page, QueryWrapper<RailwayProjectTaskPoint> queryWrapper) {
        IPage<RailwayProjectTaskPoint> pageList = this.page(page, queryWrapper);
        if (pageList.getRecords().size() < 1) return pageList;

        List<String> listIds = pageList.getRecords().stream().map(RailwayProjectTaskPoint::getId).collect(Collectors.toList());
        QueryWrapper<RailwayTaskPointFile> tqueryWrapper = new QueryWrapper<RailwayTaskPointFile>().select("id, taskpoint_id, file_url, file_type").in("taskpoint_id", listIds);
        List<RailwayTaskPointFile> listFile = railwayTaskPointFileService.list(tqueryWrapper);
        if (listFile.size() < 1) return pageList;

        log.info("listFile: {}", listFile);

        pageList = pageList.convert(item -> {
            String pointId = item.getId();
            // List<RailwayTaskPointFile> fileList = listFile.stream().filter();

            List<RailwayTaskPointFile> citem = listFile.stream().filter(e -> e.getTaskpointId().equals(pointId)).collect(Collectors.toList());
            log.info("citem: {}", citem);

            String imgList = "";
            String fileList = "";

            for (RailwayTaskPointFile file : citem) {
                if (file.getFileType() == 1) {
                    imgList += file.getFileUrl() + ",";
                }
            }
            if (imgList.endsWith(",")) {
                imgList = imgList.substring(0, imgList.length() - 1);
            }
            item.setImgList(imgList);
            return item;
        });

        return pageList;
    }

    @Override
    public void saveMain(RailwayProjectTaskPoint railwayProject) {
        railwayProject.setStatus(TaskPointStatusEnum.UPLOADED.getValue());
        this.save(railwayProject);
        this.updatePointFile(railwayProject);

        this.publishTaskStatusChange(railwayProject);
    }

    @Override
    public void updateMainById(RailwayProjectTaskPoint railwayProject) {
        this.updateById(railwayProject);
        this.updatePointFile(railwayProject);

        this.publishTaskStatusChange(railwayProject);
    }

    @Override
    public List<RailwayTaskPointFile> getPicsById(String pointId) {
        QueryWrapper<RailwayTaskPointFile> queryWrapper = new QueryWrapper<RailwayTaskPointFile>().eq("taskpoint_id", pointId).eq("file_type", 1);
        List<RailwayTaskPointFile> list = railwayTaskPointFileService.list(queryWrapper);
        log.info("list file: {}", list);
        return list;
    }

    @Override
    public void updateTestPointStatus(RailwayTaskPointOperationLog railwayProject) {
        log.info("RailwayTaskPointOperationLog: {}", railwayProject);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userRealname = user.getRealname();
        String testPointId = railwayProject.getTaskpointId();
        String memo = railwayProject.getMemo();
        TaskPointStatusEnum tstatus = TaskPointStatusEnum.getByValue(String.valueOf(railwayProject.getToStatus()));
        RailwayTestPointStatusVo testPointStatusVo = new RailwayTestPointStatusVo(testPointId, userRealname, memo, tstatus);
        applicationContext.publishEvent(new ProjectTaskPointStatusEvent(testPointStatusVo));

        RailwayProjectTaskPoint testPoint = this.getById(testPointId);
        TaskPointStatusEnum ostatus = TaskPointStatusEnum.getByValue(String.valueOf(testPoint.getStatus()));
        testPoint.setStatus(tstatus.getValue());
        Date curDate = DateUtils.getDate();
        if (ostatus.equals(TaskPointStatusEnum.APPROVING)) { // 复核人员 / 时间
            testPoint.setReviewBy(userRealname);
            testPoint.setReviewDate(curDate);
        }
        if (tstatus.equals(TaskPointStatusEnum.ANALYZED)) {
            testPoint.setCheckBy(userRealname);
            testPoint.setCheckDate(curDate); // 整理日期
        }
        this.updateById(testPoint);
    }

    private void publishTaskStatusChange(RailwayProjectTaskPoint railwayProject) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userRealname = user.getRealname();
        String projectId = railwayProject.getProjectId();
        String holeName = railwayProject.getHoleName();
        TaskPointStatusEnum status = TaskPointStatusEnum.UPLOADED;
        // TaskPointStatusEnum status = TaskPointStatusEnum.getByName("uploaded");

        RailwayTaskStatusVo projectTaskStatus = new RailwayTaskStatusVo(projectId, holeName, userRealname, null, status);
        // log.info("operation1: {}, operation2: {}", railwayProject, projectTaskStatus);
        log.info("update task status: {}", projectTaskStatus);
        applicationContext.publishEvent(new ProjectTaskStatusEvent(projectTaskStatus));
    }

    private void updatePointFile(RailwayProjectTaskPoint railwayProject) {
        if (oConvertUtils.isEmpty(railwayProject.getImgList()))
            return;

        this.deletePointFile(railwayProject);
        this.savePointFile(railwayProject);
    }

    private void savePointFile(RailwayProjectTaskPoint railwayProject) {
        String testPointId = railwayProject.getId();
        String imgStr = railwayProject.getImgList();
        String[] imgArray = imgStr.split(",");

        if (imgArray.length < 1) return;

        List<RailwayTaskPointFile> fileList = new ArrayList<RailwayTaskPointFile>();
        for (String url : imgArray) {
            RailwayTaskPointFile file = new RailwayTaskPointFile();
            file.setTaskpointId(testPointId);
            file.setFileUrl(url);
            file.setFileType(1); // 现场图片
            fileList.add(file);
        }

        railwayTaskPointFileService.saveBatch(fileList);
    }

    private void deletePointFile(RailwayProjectTaskPoint railwayProject) {
        QueryWrapper<RailwayTaskPointFile> queryWrapper = new QueryWrapper<RailwayTaskPointFile>().eq("taskpoint_id", railwayProject.getId());
        railwayTaskPointFileService.remove(queryWrapper);
    }

    @Override
    public RailwayDataManagementStatisticVo getWorkTestPointStatistic(RailwayDataManagementStatisticVo statistic) {
        String projectId = statistic.getProjectId();
        QueryWrapper<RailwayProjectTaskPoint> queryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("status, count(id) as total").eq("project_id", projectId).groupBy("status");
        List<Map<String, Object>> listMap = this.listMaps(queryWrapper);
        Integer qualified = 0;
        Integer analyzed = 0;
        Integer reviewd = 0;

        for (Map<String, Object> item : listMap) {
            String status = String.valueOf(item.get("status"));
            Integer total = oConvertUtils.getInt(item.get("total"));
            switch (status) {
                // case "1" :
                //     statistic.setPoint(total);
                //     break;
                case "2" :
                    qualified = qualified + total;
                    break;
                // case "3" :
                //     statistic.setAnalyzed(total);
                //     break;
                case "4" :
                    analyzed = analyzed + total;
                    break;
                case "6" :
                    reviewd = reviewd + total;
                    break;
                case "7" :
                    analyzed = analyzed + total;
                    break;
                default:
                    break;
            }
        }

        statistic.setQualified(String.valueOf(qualified));
        statistic.setAnalyzed(String.valueOf(analyzed));
        statistic.setReviewed(String.valueOf(reviewd));

        QueryWrapper<RailwayProjectTaskPoint> tqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().eq("project_id", projectId);
        Integer pointCount = this.count(tqueryWrapper);
        statistic.setPoint(String.valueOf(pointCount));

        return statistic;
    }
}
